// --------------------------------------------------------------------------------------------------------------------
// <copyright file="KukaLBR4CartesianSocController.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Hardware.KukaLBR
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;

    using Microsoft.Robotics.Manipulation;
    using Microsoft.Robotics.Manipulation.ControllerStateMachine;
    using Microsoft.Robotics.Numerics;

    using LBR4 = Microsoft.Robotics.Hardware.KukaLBR.KukaLBR4PlusCsharpDefinitionsNativeMethods;

    /// <summary>
    /// A controller for Cartesian position of the TCP of the LBR4 implementing stop on contact behavior
    /// </summary>
    public class KukaLBR4CartesianSocController : KukaLBR4CartesianPositionController
    {
        /// <summary>
        /// Number of state we enter on unexpected contact.
        /// </summary>
        private const int UnexpectedContactStateNumber = 2;

        /// <summary>
        /// Controller state machine description cache
        /// </summary>
        private static ControllerStateMachineDescription csmdCache;

        /// <summary>
        /// Determines if we have a cached copy of the controller state machine description available
        /// </summary>
        private static bool haveCachedCsmd = false;

        /// <summary>
        /// Register that stores the TCP force threshold
        /// </summary>
        private RegisterID tcpForceThresholdRegister;

        /// <summary>
        /// Initializes a new instance of the <see cref="KukaLBR4CartesianSocController"/> class.
        /// </summary>
        /// <param name="registerManager">Manager for assigning working registers.</param>
        /// <param name="desiredPose">Desired Cartesian pose.</param>
        /// <param name="maxLinearSpeedInMetersPerSec">Maximum linear Cartesian speed.</param>
        /// <param name="maxRotationalSpeedInRadPerSec">Maximum rotational Cartesian speed.</param>
        /// <param name="timeStepInMsec">FRI cycle time.</param>
        /// <param name="tcpForceThrehsoldInNewtons">TCP force threshold in newtons.</param>
        /// <returns>A set of working registers.</returns>
        public KukaLBR4CartesianSocController(
            KukaLBR4WorkingRegisterManager registerManager,
            Pose desiredPose,
            double maxLinearSpeedInMetersPerSec,
            double maxRotationalSpeedInRadPerSec,
            double timeStepInMsec,
            double tcpForceThrehsoldInNewtons)
            : base(
                registerManager,
                desiredPose,
                maxLinearSpeedInMetersPerSec,
                maxRotationalSpeedInRadPerSec,
                timeStepInMsec)
        {
            this.tcpForceThresholdRegister = RegisterID.NewWorkingRegister(
                registerManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Scalar));

            this.WorkingRegisterArray.Registers[this.tcpForceThresholdRegister.RegisterNumber][0] = 
                tcpForceThrehsoldInNewtons;
        }

        /// <summary>
        /// Builds a state machine controller
        /// </summary>
        /// <returns>A state machine based controller</returns>
        public new ControllerStateMachineDescription BuildStateMachineDescription()
        {
            if (!haveCachedCsmd)
            {
                csmdCache = base.BuildStateMachineDescription();
                haveCachedCsmd = true;
            }

            return csmdCache;
        }

        /// <summary>
        /// Builds the controller state machine used by this controller.
        /// </summary>
        /// <returns>A controller state machine.</returns>
        protected override ControllerStateMachine BuildControllerStateMachine()
        {
            ControllerStateMachine csm = base.BuildControllerStateMachine();

            // Suitable for a fault state since it maintains current position
            csm.HaltState = KukaLBR4CartesianPositionController.BuildSynchronizeFRICartesianPositionState();

            // One fault transition, which occurs when the magnitude of the estimated
            // force at the TCP exceeds the value set in scalar 5
            csm.HaltTransitions = new Transition[1];

            RegisterID[] operands = new RegisterID[2];
            operands[0] = RegisterID.NewFeedbackRegister((int)LBR4.KukaLBR4PlusFeedbackRegisters.EstimatedTCPForceTorqueRegister);
            operands[1] = this.tcpForceThresholdRegister;

            csm.HaltTransitions[0] = new Transition(
                csm.HaltState,
                (int)LBR4.KukaLBR4Operations.IsForceMagnitudeGreaterThanScalarOp,
                operands,
                new ControllerOperation[0]);

            return csm;
        }

        /// <summary>
        /// Generate inferred state.
        /// </summary>
        /// <param name="message">A feedback message.</param>
        /// <returns>Inferred state.</returns>
        protected override KukaLBR4InferredState GetInferredState(FeedbackMessageManaged message)
        {
            KukaLBR4InferredState infState = base.GetInferredState(message);

            if (message.CurrentControllerStateNumber == 2)
            {
                infState.TcpUnexpectedForceOccured = true;
            }

            return infState;
        }
    }
}
